<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 提示区域 -->
        <el-row class="add-header">
            <el-col :span="4">
                <el-button type="success" @click="goBack" size="small" round icon="el-icon-d-arrow-left">返回</el-button>
            </el-col>
            <el-col :span="20">
                <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
            </el-col>
        </el-row>
        <!-- 步骤条区域 -->
        <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <!-- tab栏区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top" >
            <el-tabs tab-position="left" :before-leave="beforeTabLeave" v-model="activeIndex" @tab-click="tabClicked">
                <el-tab-pane label="基本信息" name="0">
                      <el-form-item label="商品名称 :" prop="goods_name">
                         <el-input v-model="addForm.goods_name"></el-input>
                      </el-form-item>
                      <el-form-item label="商品价格 :" prop="goods_price">
                         <el-input v-model="addForm.goods_price"></el-input>
                      </el-form-item>
                      <el-form-item label="商品重量 :" prop="goods_weight">
                         <el-input v-model="addForm.goods_weight"></el-input>
                      </el-form-item>
                      <el-form-item label="商品数量 :" prop="goods_number">
                         <el-input v-model="addForm.goods_number"></el-input>
                      </el-form-item>
                       <el-form-item label="商品分类 :" prop="goods_cat">
                          <el-cascader clearable :options="catelist" placeholder="请选择" size="small"
                            :props="cascaderProps" @change="handleChange" v-model="addForm.goods_cat">
                          </el-cascader>
                      </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <!-- 渲染表单的Item项 -->
                    <el-form-item :label="item.attr_name" v-for="item in ManyList" :key="item.attr_id">
                         <!-- 复选框组 -->
                        <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="cb" v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for="item in OnlyList" :key="item.attr_id">
                         <el-input v-model="item.attr_vals"></el-input>
                      </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                  <el-upload
                    :action="actionUrl"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :headers="headerObj"
                    :on-success="handleSuccess"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                  <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                    <el-button type="primary" class="BtnAdd" @click="AddGoods">添加商品</el-button>
                </el-tab-pane>
             </el-tabs>
        </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%">
      <img :src="previewPath" class="previewImg">
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 基本信息验证状态
      state: '',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: 1,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      activeIndex: '0',
      // 所有分类数据
      catelist: [],
      // 动态参数
      ManyList: [],
      // 静态属性
      OnlyList: [],
      // 级联选择器属性
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      // 图片请求地址
      actionUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片请求头
      headerObj: { Authorization: window.sessionStorage.getItem('token') },
      previewPath: '',
      previewVisible: false,
      // 用户管理验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              var reg = /^-?\d{1,5}(?:\.\d{1,3})?$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入大于零小于十万不超过三位小数的数字'))
              }
            },
            trigger: 'blur'
          }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              if (Number.isInteger(Number(value)) && Number(value) > 0 && Number(value) < 999) {
                callback()
              } else {
                callback(new Error('请输入1-999的正整数'))
              }
            },
            trigger: 'blur'
          }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              if (Number.isInteger(Number(value)) && Number(value) > 0 && Number(value) < 999) {
                callback()
              } else {
                callback(new Error('请输入1-999的正整数'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.catelist = res.data
    },
    // 级联选择器选中项变化，会触发这个函数
    handleChange () {
      // 因为只选择第三级分类  所有不是第三级的时候就清空
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 监听tabs组件  当发生改变的时候触发
    beforeTabLeave (activeName, oldActiveName) {
      // console.log('即将离开的标签页名字是：' + oldActiveName)
      // console.log('即将进入的标签页名字是：' + activeName)
      // 凡是从基本信息tabs离开的时候都进行判断
      if (oldActiveName === '0') {
        this.ValidateRule()
        if (this.state) {
          if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
            this.$message.error('请先选择商品分类！'); return false
          }
        } else {
          this.$message.error('请将信息填写完整'); return false
        }
      }
    },
    // form表单验证函数
    ValidateRule () {
      this.$refs.addFormRef.validate(valid => {
        // 通过回调函数赋值一个状态给state
        valid ? this.state = true : this.state = false
      })
    },
    // 根据点击不同的tab-panl 响应不同的数据
    tabClicked () {
      switch (this.activeIndex) {
        case '1':
          this.getManyList()
          break
        case '2':
          this.getOnlyList()
          console.log(this.OnlyList)
          break
        case '3':

          break
        case '4':

          break
        default:
          break
      }
    },
    // 获取参数
    async getManyList () {
      // 获取参数
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes`, {
        params: { sel: 'many' }
      })
      if (res.meta.status !== 200) return this.$message.error('参数获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
      })
      this.ManyList = res.data
    },
    // 获取属性
    async getOnlyList () {
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes`, {
        params: { sel: 'only' }
      })
      if (res.meta.status !== 200) return this.$message.error('属性获取失败')
      this.OnlyList = res.data
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 文件列表移除文件时的钩子
    handleRemove (file) {
      // 获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 查找该条数据的索引
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      this.addForm.pics.splice(index, 1)
    },
    // 文件上传成功时的钩子
    handleSuccess (response) {
      // 获取图片的临时路径
      const picInfo = { pic: response.data.tmp_path }
      // 将新的图片路径追加到数组中
      this.addForm.pics.push(picInfo)
    },
    // 添加商品数据
    async AddGoods () {
      // 转换成字符串
      this.addForm.goods_cat = this.addForm.goods_cat.join(',')
      // 处理动态参数
      this.ManyList.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        this.addForm.attrs.push(newInfo)
      })
      // 处理静态属性
      this.OnlyList.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addForm.attrs.push(newInfo)
      })

      // 请求数据
      const { data: res } = await this.$http.post('goods', this.addForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg || '添加失败')
      this.$message.success('添加成功')
      this.$router.push('/home/goods')
    },
    // 点击返回
    goBack () {
      this.$router.go(-1)
    }
  },
  computed: {
    //   分类Id
    CateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>
<style lang="scss" scoped>
    .add-header{
        display: flex;
        align-items: center;
    }
    .el-steps{
        margin: 15px 0;
    }
    .el-checkbox{
      margin:0 5px 0 0 !important
    }
    .previewImg{
      width: 100%;
    }
    .BtnAdd{
      margin-top: 15px;
    }
</style>
